package com.xiaoxin.experience.service.tree;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoxin.experience.api.tree.model.InstanceInfo;
import com.xiaoxin.experience.service.tree.entity.InstanceEntity;
import com.xiaoxin.experience.service.tree.mapper.InstanceMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author xiaoxin
 */
@Service
public class InstanceService extends ServiceImpl<InstanceMapper, InstanceEntity>
{
    @Transactional(isolation = Isolation.READ_COMMITTED)
    public List<InstanceInfo> getInstanceList()
    {
        return baseMapper.selectList(null).stream().map(InstanceEntity::toInfo).collect(Collectors.toList());
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean saveOrUpdate(InstanceInfo instanceInfo)
    {
        if (instanceInfo == null)
        {
            return false;
        }
        return saveOrUpdate(new InstanceEntity(instanceInfo));
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean deleteInstance(Integer id)
    {
        return removeById(id);
    }

    public void deleteByDirectoryId(Integer id)
    {
        baseMapper.delete(lambdaQuery().eq(InstanceEntity::getDirectoryId, id).getWrapper());
    }
}
